package com.amazon.shop.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.amazon.shop.bean.dto.BaseGroup;
import com.amazon.shop.bean.dto.LoginFrom;
import com.amazon.shop.bean.dto.UserFrom;
import com.amazon.shop.bean.entity.RelUserStore;
import com.amazon.shop.bean.entity.User;
import com.amazon.shop.bean.enums.ResultEnum;
import com.amazon.shop.bean.vo.PageVO;
import com.amazon.shop.bean.vo.Ret;
import com.amazon.shop.service.*;
import com.amazon.shop.util.ResultUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lzj
 * @since 2021-02-26
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService tblUserService;

    @Autowired
    private IStoreService storeService;

    @Autowired
    private IRelUserStoreService relUserStoreService;

    @Autowired
    private IEmailmodelService emailService;

    @Autowired
    private IPriductService priductService;


    @RequestMapping("/login")
    public Ret login(@Validated LoginFrom loginFrom, HttpServletRequest request, HttpServletResponse response){
        return tblUserService.login(loginFrom,request, response);
    }
    @GetMapping("/logOut")
    public Ret logOut(String username, HttpServletRequest request, HttpServletResponse response){
        if (StrUtil.isBlank(username)) {
            return ResultUtil.error("-1","-1","username必传");
        }
        return tblUserService.logOut(username,request, response);
    }

    @RequestMapping("/get")
    public Ret get(@Validated(value = {BaseGroup.get.class}) UserFrom userFrom){
        QueryWrapper queryWrapper = new QueryWrapper();
        Integer disable = userFrom.getDisable();
        if (disable!=null) {
            queryWrapper.eq("disable",disable);
        }
        queryWrapper.ne("ismanager",1);
        if (StrUtil.isNotBlank(userFrom.getUsername())) {
            queryWrapper.eq("username",userFrom.getUsername());
        }
        if (StrUtil.isNotBlank(userFrom.getNickname())) {
            queryWrapper.eq("nickname",userFrom.getNickname());
        }
        if (StrUtil.isNotBlank(userFrom.getEmail())) {
            queryWrapper.eq("email",userFrom.getEmail());
        }
        Page<User> page = new Page(userFrom.getCurrentNum(),userFrom.getPageSize());
        page = tblUserService.page(page,queryWrapper);
        PageVO<User> pageVo = new PageVO(page);
        return ResultUtil.success(pageVo);
    }

    @RequestMapping("/add")
    public Ret add(@Validated(value = {BaseGroup.add.class}) UserFrom userFrom) {
        if(userFrom.getOismanager()!=1){
            return ResultUtil.error(ResultEnum.FAILURE.getCode(),ResultEnum.FAILURE.getServecode(),"非管理员账号不允许操作");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<> ();
        queryWrapper.eq("username",userFrom.getUsername());
        queryWrapper.or().eq("email",userFrom.getEmail());
        int count = tblUserService.count(queryWrapper);
        if (count>0) {
            return ResultUtil.error(ResultEnum.EXISTERROR.getCode(),ResultEnum.EXISTERROR.getCode(),"邮箱或账号已存在");
        }

        User user = new User();
        BeanUtil.copyProperties(userFrom,user);
        user.setPassword(SecureUtil.md5(userFrom.getPassword()));
        Date date = new Date(Long.parseLong(userFrom.getTimestamp()));
        user.setCreatetime(date);
        user.setUpdatetime(date);
        return tblUserService.save(user)?ResultUtil.success():ResultUtil.error(ResultEnum.FAILURE);
    }
    @RequestMapping("/update")
    public Ret update(@Validated(value = {BaseGroup.update.class}) UserFrom userFrom) {
        if(userFrom.getOismanager()!=1){
            return ResultUtil.error(ResultEnum.FAILURE.getCode(),ResultEnum.FAILURE.getServecode(),"非管理员账号不允许操作");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<> ();
        if (StrUtil.isNotBlank(userFrom.getEmail())) {
            queryWrapper.ne("id",userFrom.getId());
            queryWrapper.eq("email",userFrom.getEmail());
            int count = tblUserService.count(queryWrapper);
            if (count>0) {
                return ResultUtil.error(ResultEnum.EXISTERROR.getCode(),ResultEnum.EXISTERROR.getServecode(),"邮箱已存在");
            }
        }

        UpdateWrapper<User> updateWrapper = new UpdateWrapper<> ();
        updateWrapper.eq("id",userFrom.getId());
        String nickname = userFrom.getNickname();
        String password = userFrom.getPassword();
        String email = userFrom.getEmail();
        Integer disable = userFrom.getDisable();
        if (StrUtil.isNotBlank(nickname)) {
            updateWrapper.set("nickname",nickname);
        }
        if (StrUtil.isNotBlank(password)) {
            password = SecureUtil.md5(userFrom.getPassword());
            updateWrapper.set("password",password);
        }
        if (StrUtil.isNotBlank(email)) {
            updateWrapper.set("email",email);
        }
        if (disable!=null) {
            updateWrapper.set("disable",disable);
        }
        if (disable!=null) {
            updateWrapper.set("disable",disable);
        }
        updateWrapper.set("updatetime",new Date());
        return tblUserService.update(updateWrapper)?ResultUtil.success():ResultUtil.error(ResultEnum.FAILURE);
    }

    @RequestMapping("/updatePassword")
    public Ret updatePassword(String username, String newpwd,String oldpwd) {
        User byId = tblUserService.getOne(new QueryWrapper<User>().eq("username",username));
        if(byId==null){
            return ResultUtil.error(ResultEnum.USERERROR);
        }
        if(StrUtil.isBlank(username)||StrUtil.isBlank(newpwd)||StrUtil.isBlank(oldpwd)){
            return ResultUtil.error("-1","-1","参数缺失");
        }
        String encryptPwd = SecureUtil.md5(oldpwd);
        String password = byId.getPassword();
        if (!encryptPwd.equals(password)) {
            return ResultUtil.error("-1","-1","密码错误");
        }
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<> ();
        updateWrapper.eq("username",username);
        updateWrapper.set("password",SecureUtil.md5(newpwd));
        boolean bln = tblUserService.update(updateWrapper);
        return bln?ResultUtil.success():ResultUtil.error();
    }


    @RequestMapping("/del")
    @Transactional
    public Ret del(@Validated(value = {BaseGroup.del.class}) UserFrom userFrom) {
        if(userFrom.getOismanager()!=1){
            return ResultUtil.error(ResultEnum.FAILURE.getCode(),ResultEnum.FAILURE.getServecode(),"非管理员账号不允许操作");
        }
        Integer id = userFrom.getId();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.select("storeid");
        queryWrapper.eq("userid",id);
        List<RelUserStore> list = relUserStoreService.list(queryWrapper);
        if(list!=null&&list.size() > 0){
            relUserStoreService.remove(queryWrapper);
            List<Integer> collect = list.stream().map(RelUserStore::getStoreid).collect(Collectors.toList());
            queryWrapper.clear();
            queryWrapper.in("id",collect);
            storeService.remove(queryWrapper);

            queryWrapper.clear();
            queryWrapper.eq("userid",id);
            emailService.remove(queryWrapper);

            queryWrapper.clear();
            queryWrapper.in("storeid",collect);
            priductService.remove(queryWrapper);

            queryWrapper.clear();
            queryWrapper.in("id",collect);
            storeService.remove(queryWrapper);
        }
        tblUserService.removeById(id);
        return ResultUtil.success();
    }
}
